import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jicaimao_flutter/entity/my_nickname_bean.dart';
import 'package:jicaimao_flutter/utils/api_address.dart';
import 'package:jicaimao_flutter/utils/event_bus.dart';
import 'package:jicaimao_flutter/utils/http_utils.dart';
import 'package:jicaimao_flutter/utils/sp_key.dart';
import 'package:jicaimao_flutter/utils/sp_utils.dart';
import 'package:jicaimao_flutter/utils/toast.dart';

class MyNickname extends StatefulWidget {
  @override
  _MyNicknameState createState() => _MyNicknameState();
}

class _MyNicknameState extends State<MyNickname> {
  bool isClearshow = false;
  final nickname_controller = TextEditingController();
  EventBus eventBus = new EventBus();

  _Preservation() {
    String nickname_str = nickname_controller.text;
    if (nickname_str == null || nickname_str == "") {
      Toast.toast(context, "请输入昵称");
      return;
    }

//    String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
//    if (nickname_str.contains(regEx)) {
//      Toast.toast(context, "用户名只能输入中文或英文字母、数字");
//      return;
//    }

    String userId = SpUtils.getString(SpKey.KEY_USER_ID);
// 网络请求数据
    _loadData(userId);

  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Color(0xFFF6F5F5),
        appBar: AppBar(
          centerTitle: true,
          backgroundColor: Colors.white,
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              color: Colors.grey,
            ),
            onPressed: () => Navigator.pop(context),
          ),
          title: Text(
            '修改昵称',
            style: TextStyle(
              fontSize: 16,
              color: Colors.black,
            ),
          ),
          actions: <Widget>[
            new Container(
              height: 50.0,
              padding: EdgeInsets.fromLTRB(15.0, 20.0, 15.0, 0.0),
              child: GestureDetector(
                onTap: () {
                  _Preservation();
                },
                child: Text(
                  '保存',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.black,
                  ),
                ),
              ),
            ),
          ],
        ),
        body: Column(
          children: <Widget>[
            _inputNickname(),
            Container(
              margin: EdgeInsets.fromLTRB(10, 10, 10, 0),
              child: Text('只能输入中文或英文字母、数字，限制16个字符，一个汉字为两个字符'),
            ),
          ],
        ),
      ),
    );
  }

  ///输入昵称
  _inputNickname() {
    return Container(
        height: 45,
        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
        margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
        color: Colors.white,
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: TextField(
                onChanged: (text) {
                  if (text.length > 0) {
                    setState(() {
                      isClearshow = true;
                    });
                  }
                },
                controller: nickname_controller,
                inputFormatters: [LengthLimitingTextInputFormatter(16)],
                maxLength: 16,
                maxLines: 1,
                keyboardType: TextInputType.text,
                decoration: InputDecoration(
                    hasFloatingPlaceholder: false,
                    counterText: '',
                    border: InputBorder.none,
                    hintText: '请输入昵称',
                    disabledBorder: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none),
                style: TextStyle(
                  color: Color(0xff666666),
                  fontSize: 16.0,
                ),
              ),
            ),
            GestureDetector(
              child: Container(
                width: 40,
                height: 40,
                padding: EdgeInsets.fromLTRB(20, 10, 0, 10),
                child: Image.asset(isClearshow ? 'images/icon_error.png' : ''),
              ),
              onTap: () {
                nickname_controller.clear();
                setState(() {
                  isClearshow = !isClearshow;
                });
              },
            )
          ],
        ));
  }

  /// 网络获取数据
  Future _loadData(String userId) async {
    String url = NetAddress.updateNickName;
    String nickname_str = nickname_controller.text;
    var data = {'userId': userId, 'nickName': nickname_str};
    var respone = await HttpUtil().post(url, data: data);
    setState(() {
      MyNicknameBean _mBean = MyNicknameBean.fromJson(json.decode(respone));
      if (_mBean.code == "200") {
        eventBus.fire(new MyEvent(nickname_str));
        Navigator.pop(context, nickname_str);
      }else{
        Toast.toast(context, _mBean.msg);
      }
    });
  }

}

class MyEvent {
  String text;
  MyEvent(this.text);
}
